import json

def create_headers(info):
    """生成HTTP Headers"""
    mime = info["mime"]
    size = info["size"]
    cache_age = 120  # 默认缓存120s

    header_str = ""

    head = f"HTTP/1.1 200 OK\r\n"

    common_headers = {
        "Content-Type": mime,
        "Content-Length": size,
    }

    etag = info["etag"]
    cache_headers = {
        "Cache-Control": f"max-age={cache_age}",
        "ETag": f"{etag}",
    }

    header_str += head

    for ch_key in common_headers:
        header_str += f"{ch_key}: {common_headers[ch_key]}" + "\r\n"

    for ch_key in cache_headers:
        header_str += f"{ch_key}: {cache_headers[ch_key]}" + "\r\n"

    return f"{header_str}\r\n"

def create_http_headers(payload):
    """生成http response header"""
    content = json.dumps(payload)
    byte_data = bytes(content, "utf-8")
    length = len(byte_data)
    header_str = f"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {length}\r\n\r\n"
    return header_str

def create_http_response(payload):
    content = json.dumps(payload)
    byte_data = bytes(content, "utf-8")
    return byte_data

async def return_json_data(writer, data):
    """写入json数据"""
    response = create_http_headers(data)
    writer.write(response)
    writer.write(create_http_response(data))

async def return_json_error(writer):
    """返回json错误"""
    res = {"value":"error"}
    await return_json_data(writer, res)

async def return_json_ok(writer):
    """返回json成功"""
    res = create_http_headers({"value":"ok"})
    await return_json_data(writer, res)






